package cn.xiaoliu.org.service.impl;

import cn.xiaoliu.basic.service.impl.BaseServiceImpl;
import cn.xiaoliu.org.domain.Department;
import cn.xiaoliu.org.mapper.DepartmentMapper;
import cn.xiaoliu.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    //1.基本的CRUD通过继承得到

    //2.扩展的业务方法实现,自己在这里添加
    // 如果基本的CRUD需求更高,就在子类实现中复写方法即可
    //添加
    @Override
    @Transactional
    public void add(Department department) {

        departmentMapper.save(department);
        //调用方法
        this.update(department);

    }

    //修改
    @Override
    @Transactional
    public void update(Department department) {
        //新增顶级部门  dirPath：/自己的id
        String dirPath = "";
        if (department.getParent()==null){
            dirPath = "/"+department.getId();
        }else {
            //如果不是顶级部门  dirPath：/父亲部门的dirPath/自己的id
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath()+"/"+department.getId();
        }
        //再设置进去
        department.setDirPath(dirPath);

        departmentMapper.update(department);
    }
    @Override
    public List<Department> queryDeptTree() {
        return departmentMapper.loadDeptTree();
    }
}
